<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Exception;

class AdminController extends Controller {

	/*
	*	构造函数
	*/
	function __construct(){
		date_default_timezone_set('PRC'); 
		$this->admin = Db::table('admin');
		$path = app_path();
		$this->planPath =$path."/Http/Controllers/Admin/";
	}

	/*
	*	添加管理员界面
	*/
	public function add(Request $request){
		$input = $request->input();

		unset($input['repasswd']);

		if(!empty($input['id'])){
			if(!empty($input['pwd'])){
				$input['pwd'] = password_hash($input['pwd'], PASSWORD_BCRYPT);
			}else{
				unset($input['pwd']);
			}
			$this->admin->where("id","=",$input['id'])->update($input);
		}else {
			if(!$input['account'] || !$input['pwd'])throw new Exception("账号或密码为空!");
			$da = $this->admin->where('account',"=",$input['account'])->first();
			if(isset($da->id)) throw new Exception("账号已存在！");

			$input['pwd'] = password_hash($input['pwd'], PASSWORD_BCRYPT);
			$input['add_time'] = time();
			$this->admin->insert($input);
		}

		return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '修改成功！'
        ]);

	}

	/*
	*	编辑管理员界面
	*/
	public function edit(Request $request,$id){
		$res = $this->admin->where('id',"=",$id)->first();
		$list = Db::table('admin_role')->orderBy('role_id','desc')->get();
		return 	view('admin/admin_edit',['list'=>$list,'res'=>$res,'id'=>$id]);
	}

	/**
	 *  添加管理员界面
	 */
	public function admin_add(){
		$list = Db::table('admin_role')->orderBy('role_id','desc')->get();
		return 	view('admin/admin_add',['list'=>$list]);
	}

	/*
	*	管理员列表
	*/
	public function li(){
		$list = $this->admin->join('admin_role','admin_role.role_id','=','admin.role_id')->paginate(15);

		return view('admin/admin_li',['list'=>$list]);
	}

	/*
	*	删除管理员
	*/
	public function del(Request $request,$id){
		if(empty($id)) throw new Exception("参数有误!");
		$da=$this->admin->where("id","=",$id)->first();
		if(!isset($da->id)) throw new Exception("账号有误！");
		if($da->id==1) throw new Exception("超级管理不能删除", 1);
		$this->admin->where("id","=",$id)->delete();
		return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '删除成功！'
        ]);
	}

	/*
	*	禁用管理员
	*/
	public function ban(Request $request,$id){
		if(!$id) throw new Exception("参数有误！");;
		$da=$this->admin->where('id',"=",$id)->first();
		if(!$da->id) throw new Exception("账号有误！");;
		$act_list = Db::table('admin_role')->where('role_id','=',$da->role_id)->first();
		if($act_list->act_list=='all') throw new Exception("超级管理员不能修改！");
		if($da->status==1){
			$res=$this->admin->where('id',"=",$id)->update(["status"=>0]);
		}else{
			$res=$this->admin->where('id',"=",$id)->update(["status"=>1]);
		}
		return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
	}

	//权限列表
	public function right_list(Request $request){
		$input = $request->input();
		$where = [];
		$name = '';
		if (!empty($input['name'])) {
			$name = $input['name'];
			$where[] = ['name','like',"%{$input['name']}%"];
		}

		//权限组
		$right_list = Db::table('system_menu')->where($where)->paginate(15);
		$system_menu_count = Db::table('system_menu')->where($where)->count();
		return view('admin/admin_right_list',['right_list'=>$right_list,'system_menu_count'=>$system_menu_count,'name'=>$name]);
	}

	//添加权限模板
	public function admin_add_right(){
		$info = [];
		
		$planList = array();
		$dirRes   = opendir($this->planPath);
		while($dir = readdir($dirRes))
		{
			if(!in_array($dir,array('.','..','.svn')))
			{
				$planList[] = basename($dir,'.php');
			}
		}

		return view('admin/admin_add_right',['data'=>$info,'planList'=>$planList]);
	}

	//编辑权限模板
	public function admin_edit_right(Request $request,$id){
		if($id){
			$info = Db::table('system_menu')->where('id','=',$id)->first();
			$info->right = explode(',', $info->right);
		}

		$planList = array();
		$dirRes   = opendir($this->planPath);
		while($dir = readdir($dirRes))
		{
			if(!in_array($dir,array('.','..','.svn')))
			{
				$planList[] = basename($dir,'.php');
			}
		}

		return view('admin/admin_edit_right',['data'=>$info,'planList'=>$planList,'id'=>$id]);
	}


	//编辑权限
	public function edit_right_do(Request $request){
		$data = $request->input();
		$data['right'] = implode(',',$data['right']);
		if(!empty($data['id'])){
			Db::table('system_menu')->where('id','=',$data['id'])->update($data);
		}else{
			if(Db::table('system_menu')->where('name','=',$data['name'])->count()>0)throw new Exception("该权限名称已添加，请检查");
			unset($data['id']);
			Db::table('system_menu')->insert($data);
		}

		return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '删除成功！'
        ]);
	}

	//删除权限
	public function right_del(Request $request,$id){
		if(!empty($id)){
			Db::table('system_menu')->where('id','=',$id)->delete();
		}else{
			throw new Exception("参数有误!", 1);
		}

		return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '删除成功！'
        ]);
	}

	//控制器获取下面的function
	function ajax_get_action(Request $request)
	{
		$input = $request->input();
		$control = $input['controller'];
		
		$advContrl = get_class_methods('App\Http\Controllers\Admin\\'.str_replace('.php','',$control));
		$baseContrl = get_class_methods('App\Http\Controllers\Controller');
		$baseContrl[] = '__construct';

		$diffArray  = array_diff($advContrl,$baseContrl);

		$html = '';
		foreach ($diffArray as $val){
			$html .= "<option value='".$val."'>".$val."</option>";
		}
		exit($html);
	}

	//角色管理
	public function role(){
		$list = Db::table('admin_role')->orderBy('role_id','desc')->paginate(10);
		$admin_role_count = Db::table('admin_role')->count();
		return view('admin/admin_role',['list'=>$list,'admin_role_count'=>$admin_role_count]);
	}

	//添加角色
	public function add_role(){
		$modules = [];
		$right = Db::table('system_menu')->orderBy('id','desc')->get();
		foreach ($right as $val){
			$modules[$val->group][] = $val;
		}
		return view('admin/admin_role_add',['modules'=>$modules]);
	}

	//角色详情
	public function role_info(Request $request,$id){
		$role_id =$id;
		$detail = array();
		$modules= [];
		$detail = Db::table('admin_role')->where("role_id",'=',$role_id)->first();
		$detail->act_list = explode(',', $detail->act_list);

		$right = Db::table('system_menu')->orderBy('id','desc')->get();
		foreach ($right as $val){
			if(!empty($detail)){
				$val->enable = in_array($val->id, $detail->act_list);
			}
			$modules[$val->group][] = $val;
		}

		return view('admin/admin_role_info',['detail'=>$detail,'modules'=>$modules,'id'=>$id]);
	}


	//角色保存
	public function roleSave(Request $request){
		$data = $request->input();
		$res = $data['data'];
		if(!isset($data['right'])){
			$data['right']='';
		}
		$res['act_list'] = is_array($data['right']) ? implode(',', $data['right']) : '';

		if(empty($res['role_id'])){
			$r = Db::table('admin_role')->insertGetId($res);
			$data['role_id']=$r;
		}else{
			$r =Db::table('admin_role')->where('role_id','=',$res['role_id'])->update($res);
		}
		
		return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
	}


	//删除角色
	public function roleDel(Request $request,$id){
		$where[] = ['role_id','=',$id];
		$admin = $this->admin->where($where)->first();
		if(isset($admin->id))throw new Exception("请先清空所属该角色的管理员!");
			
		Db::table('admin_role')->where("role_id",'=',$id)->delete();

		return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
	}
}